import subprocess
import tempfile


def execute_and_test_python_code(code, test_cases=None, timeout=10):
    """
    测试Python代码的测试用例

    参数:
        code (str): 要测试的Python代码
        test_cases (list): 测试样例列表，每个样例为(input, expected_output)元组
        timeout (int): 执行超时时间(秒)，默认10秒

    返回:
        dict: 包含测试结果的字典，格式为:
            {
                'test_results': [
                    {
                        'input': str,
                        'expected': str,
                        'actual': str,
                        'error': str,
                        'passed': bool
                    },
                    ...
                ],
                'all_passed': bool
            }
    """
    if test_cases is None:
        test_cases = []
    
    
    # 创建临时文件
    with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False) as tmp:
        tmp.write(code)
        tmp_path = tmp.name

    test_results = []
    all_passed = True

    try:
        # 对每个测试用例进行测试
        for input_data, expected_output in test_cases:
            try:
                process = subprocess.run(
                    ['python3', tmp_path],
                    input=input_data,
                    capture_output=True,
                    text=True,
                    timeout=timeout
                )

                actual_output = process.stdout.strip()
                error_output = process.stderr.strip()
                # actual_output
                passed = actual_output == expected_output.strip() and not error_output

                if not passed:
                    all_passed = False

                test_results.append({
                    'input': input_data,
                    'expected': expected_output,
                    'actual': actual_output,
                    'error': error_output,
                    'passed': passed
                })

            except subprocess.TimeoutExpired:
                test_results.append({
                    'input': input_data,
                    'expected': expected_output,
                    'actual': 'TIMEOUT',
                    'error': 'Execution timed out',
                    'passed': False
                })
                all_passed = False
            except Exception as e:
                test_results.append({
                    'input': input_data,
                    'expected': expected_output,
                    'actual': f'ERROR: {str(e)}',
                    'error': str(e),
                    'passed': False
                })
                all_passed = False

        return {
            'test_results': test_results,
            'all_passed': all_passed
        }

    finally:
         pass

def print_test_result(result):
    # 打印测试结果
    print("\n测试结果:")
    for i, test in enumerate(result['test_results'], 1):
        print(f"  测试用例 {i}:")
        print(f"    输入: {test['input']}")
        print(f"    预期输出: {test['expected']}")
        print(f"    实际输出: {test['actual']}")
        print(f"    错误输出: {test['error']}")
        print(f"    通过: {'是' if test['passed'] else '否'}")

    # 打印整体测试结果
    print(f"\n所有测试用例是否通过: {'是' if result['all_passed'] else '否'}")

if __name__ == '__main__':
    import agent
    plan_1=agent.agent_planer("python","编程学习")
    print(plan_1.plans[1])
    print(plan_1.intro[1])
    proj_1=agent.agent_project_maker(plan_1,1)
    code=agent.agent_code_completer(proj_1)
    print(proj_1.md)
    print(code)
    test_case=agent.agent_testcase_generator(proj_1)
    for i, (item1, item2) in enumerate(test_case, 1):

        print(f"  预期输入: {item1}")
        print(f"  预期输出: {item2}")
        print()  # 添加空行分隔
    result=execute_and_test_python_code(code,test_case)
    print_test_result(result)
